//!
//! Copyright (c) 2024-2999 北京心月狐科技有限公司 All rights reserved.
//!
//! https://www.mxxshop.com
//!
//! Licensed 并不是自由软件，未经许可不能去掉 MxxShop 相关版权
//!
//! 版权所有，侵权必究！
//!

use actix_session::Session;
use actix_web::{HttpResponse, web, get, post};
use actix_web::http::header::ContentType;
use crate::core::errors::error::Result;
use bcrypt::verify;
use minijinja::context;
use crate::core::constant::user_const::SESSION_USER_KEY;
use crate::core::service::template_service::get_template;
use crate::core::web::response::ResVO;
use crate::modules::user::entity::user_model::{UserLoginRequest, UserLoginResponse, UserSaveRequest};
use crate::modules::user::service::user_service;

#[get("/user/login")]
pub async fn user_login() -> Result<HttpResponse> {
    let ctx = context!(
        title => "MxxShop",
    );
    let out = get_template("default/user/login.html", ctx)?;
    Ok(HttpResponse::Ok().content_type(ContentType::html()).body(out))
}

#[post("/user/login")]
pub async fn post_login(session: Session, item: web::Json<UserLoginRequest>) -> Result<HttpResponse> {
    let user_result = user_service::select_by_username(&item).await;
    match user_result {
        Ok(user) => {
            match user {
                None => {
                    Ok(HttpResponse::Ok().json(ResVO::<String>::error_msg("用户不存在".to_string())))
                }
                Some(user_info) => {
                    let valid = verify(&item.password.clone().unwrap_or_default(), &user_info.password.unwrap_or_default()).unwrap_or_default();
                    if !valid {
                        return Ok(HttpResponse::Ok().json(ResVO::<String>::error_msg("密码不正确".to_string())));
                    }

                    let logger_user = UserLoginResponse {
                        id: user_info.id.clone(),
                        username: user_info.user_name.clone(),
                    };
                    let logger_string = serde_json::to_string(&logger_user).unwrap_or_default();
                    session.insert(SESSION_USER_KEY, logger_string)?;
                    Ok(HttpResponse::Ok().json(ResVO::<String>::error_msg("登录成功".to_string())))
                }
            }
        }
        Err(err) => {
            Ok(HttpResponse::Ok().json(ResVO::<String>::error_msg(err.to_string())))
        }
    }
}

///用户注册
pub async fn get_signup() -> Result<HttpResponse> {
    let ctx = context!(
        title => "MxxShop",
    );
    let out = get_template("default/user/signup.html", ctx)?;
    Ok(HttpResponse::Ok().content_type(ContentType::html()).body(out))
}

pub async fn post_signup(item: web::Json<UserSaveRequest>) -> HttpResponse {
    let user_save = item.0;
    let result = user_service::add_user(user_save).await;

    return HttpResponse::Ok().json(ResVO::<u64>::handle_result(result));
}

#[get("/user/index")]
pub async fn user_index(session: Session) -> Result<HttpResponse> {
    

    let ctx = context!(
        title => "MxxShop",
    );
    let out = get_template("default/user/index.html", ctx)?;
    Ok(HttpResponse::Ok().content_type(ContentType::html()).body(out))
}

#[get("/user/logout")]
pub async fn user_logout(session: Session) -> Result<HttpResponse> {
    session.remove(SESSION_USER_KEY);
    Ok(HttpResponse::Ok().json(ResVO::<String>::error_msg("已退出".to_string())))
}

#[get("/user/forgot")]
pub async fn user_forgot() -> Result<HttpResponse> {
    let ctx = context!(
        title => "MxxShop",
    );
    let out = get_template("default/user/forgot.html", ctx)?;
    Ok(HttpResponse::Ok().content_type(ContentType::html()).body(out))
}